package com.itheima.reggie.web.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.dto.category.CategoryAddDTO;
import com.itheima.reggie.entity.dto.category.CategoryUpdateDTO;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.web.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 *
 * @author WuQiang
 * @since 2022-08-13
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("page")
    public R page(@RequestParam("page") Long pageNum, Long pageSize) {
        Page page = categoryService.page(pageNum, pageSize);
        return R.success("分页查询成功", page);
    }

    /**
     * 保存分类，分类名称唯一性校验
     * @param dto
     * @return
     */
    @PostMapping
    public R save(@RequestBody CategoryAddDTO dto) {
        Boolean flag = categoryService.saveCategory(dto);
        if (flag) {
            return R.success("新增成功");
        }
        return R.error("新增失败");
    }

    /**
     * 修改分类，name唯一性校验
     * @param dto
     * @return
     */
    @PutMapping
    public R update(@RequestBody CategoryUpdateDTO dto) {
        Boolean flag = categoryService.updateCategory(dto);
        if (flag) {
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    public R delete( Long id){
        Boolean flag = categoryService.delCategory(id);
        if (flag) {
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    @GetMapping("/list")
    public R getCategoryList(Integer type){
/*        //参数校验
        if (ObjectUtils.isEmpty(type)){
//            throw new BusinessException("参数非法");
            type = 1;
        }
        if (type != 1 && type != 2 ){
            throw new BusinessException("参数非法");
        }*/
        List<Category> categories = categoryService.getList(type);
        return R.success("查询分类成功",categories);
    }

}

